package com.erp.fin.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.erp.common.controller.BaseController;
import com.erp.common.utils.*;
import com.erp.fin.domain.*;
import com.erp.fin.service.PricetypeService;
import com.erp.fin.service.ReimInfoService;
import com.erp.fin.service.ReimburseTypeService;
import com.erp.itm.domain.DeviceAmountTwoDO;
import com.erp.itm.domain.ProjectDO;
import com.erp.itm.domain.ProjectLogDO;
import com.erp.itm.service.DeviceAmountTwoService;
import com.erp.itm.service.ProjectLogService;
import com.erp.itm.service.ProjectService;
import com.erp.system.dao.UserRoleDao;
import com.erp.system.domain.DeptDO;
import com.erp.system.domain.UserDO;
import com.erp.system.service.DeptService;
import com.erp.system.service.UserService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.erp.fin.service.ReimService;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-07-31 16:40:04
 */
 
@Controller
@RequestMapping("/fin/reim")
public class ReimController extends BaseController {
	@Autowired
	private ReimService reimService;

	@Autowired
	private DeptService sysDeptService;

	@Autowired
	private UserService userService;

	@Autowired
	private ReimInfoService reimInfoService;

	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectLogService projectLogService;
	/**
	 * 费用类型
	 */
	@Autowired
	private PricetypeService pricetypeService;

	@Autowired
	private ReimburseTypeService reimburseTypeService;


	@Autowired
	private DeviceAmountTwoService deviceAmountTwoService;

	@GetMapping()
	String Reim(){
	    return "fin/reim/reim";
	}

	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		setOpenParms(params);
		Query query = new Query(params);
		List<ReimDO> reimList = reimService.list(query);
		int total = reimService.count(query);
		PageUtils pageUtils = new PageUtils(reimList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	String add(Model model){
		String reimNumber = "KPJD-"+ StringUtils.getCtime();
		model.addAttribute("reimNumber", reimNumber);
			//查询部门领导
			int mgrcount = userService.isManager(getUserId());
			if(mgrcount>0){
				Map<String, Object> map = new HashMap<>();
				map.put("deptId",16);
				List<UserDO> userDOList = userService.list(map);
				model.addAttribute("userDOList", userDOList);
			}else{
				List<UserDO> userDOList = userService.getlistBymanager();
				model.addAttribute("userDOList", userDOList);
			}
	    return "fin/reim/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id,Model model){
		getEdit(id, model);
		return "fin/reim/edit";
	}

	@GetMapping("/printInfo/{id}")
	String printInfo(@PathVariable("id") Long id,Model model){
		getEdit(id, model);
		return "fin/reim/print";
	}


	private void getEdit(@PathVariable("id") Long id, Model model) {
		ReimDO reim = reimService.get(id);
		List<ReimInfoDO> reimInfoDOList = reimInfoService.findReimInfoByreimid(id);
		for (ReimInfoDO reimInfo:reimInfoDOList) {
			if(reimInfo.getInvoiceType() != null){
				ReimburseTypeDO reimburseTypeDO = reimburseTypeService.get(Long.valueOf(reimInfo.getInvoiceType()));
				reimInfo.setUserNameCreate(reimburseTypeDO.getName());
			}else{
				reimInfo.setUserNameCreate(null);
			}
		}

		ReimDto reimDto =ReimDto.builder()
				.reimAmount(reim.getReimAmount())
				.reimAmountCap(reim.getReimAmountCap())
				.reimDate(reim.getReimDate())
				.reimNumber(reim.getReimNumber())
				.reimTypeid(reim.getReimTypeid())
				.reimUserid(reim.getReimUserid())
				.reimUsername(reim.getReimUsername())
				.deptId(reim.getDeptId())
				.deptName(reim.getDeptName())
				.gmtCreate(reim.getGmtCreate())
				.id(reim.getId())
				.writeoff(reim.getWriteoff())
				.userNameCreate(reim.getUserNameCreate())
				.userIdCreate(reim.getUserIdCreate())
				.remark(reim.getRemark())
				.isInvoice(reim.getIsInvoice())
				.reimInfoDOList(reimInfoDOList)
				.depetLeaderid(reim.getDepetLeaderid())
				.depetLeadername(reim.getDepetLeadername())
				.companId(reim.getCompanId())
				.companName(reim.getCompanName())
				.build();
		model.addAttribute("reimDto", reimDto);
		//1.查询报销人
		List<UserDO> userDOList = userService.getlist(null);
		model.addAttribute("userDOList", userDOList);

		//1.查询部门
		List<DeptDO> deptDOList = sysDeptService.list(null);
		model.addAttribute("deptDOList", deptDOList);
	}

	/**
	 * 保存
	 * reimAmountCap
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save(ReimDto reimDto){
		if(reimDto != null){
			if(reimDto.getReimAmount() != null && reimDto.getReimAmount().compareTo(BigDecimal.ZERO)==1){
				String reimAmountCap = NumberToChineseUtil.getChineseNumber(reimDto.getReimAmount().doubleValue());
				reimDto.setReimAmountCap(reimAmountCap);
			}
			ReimDO reimDO = ReimDO.builder()
					.isInvoice(reimDto.getIsInvoice())
					.deptId(reimDto.getDeptId())
					.reimAmount(reimDto.getReimAmount())
					.reimAmountCap(reimDto.getReimAmountCap())
					.reimDate(reimDto.getReimDate())
					.reimNumber(reimDto.getReimNumber())
					.writeoff(reimDto.getWriteoff())
					.reimTypeid(reimDto.getReimTypeid())
					.reimUserid(reimDto.getReimUserid())
					.remark(reimDto.getRemark())
					.userIdCreate(getUserId())
					.userNameCreate(getUser().getName())
					.gmtCreate(new Date())
					.status(1)
					.build();
			//查询部门领导
			List<UserDO> userDOList =  userService.getManager(getUser().getDeptId());
			if(userDOList != null && userDOList.size()>0){
				reimDO.setDepetLeaderid(userDOList.get(0).getUserId());
				reimDO.setDepetLeadername(userDOList.get(0).getName());
			}
			reimDO.setDeptId(getUser().getDeptId());
			reimDO.setDeptName(sysDeptService.getName(getUser().getDeptId()));
			reimDO.setReimUserid(getUserId());
			reimDO.setReimUsername(getUser().getName());
			reimDO.setCompanId(getUser().getCompanyId());
			reimDO.setCompanName(getUser().getCompanyName());
			int id = reimService.save(reimDO);
			if(id>0){
				List<ReimInfoDO> reimInfoDOList = reimDto.getReimInfoDOList();
				if(reimInfoDOList != null && reimInfoDOList.size()>0){
					//开始保存明细信息
					for (ReimInfoDO reininfo:reimInfoDOList) {
						reininfo.setReimId(reimDO.getId());
						//查询项目名称
						if(reininfo.getProjectId() != null && reininfo.getProjectId()>0){
							ProjectDO projectDO = projectService.get(reininfo.getProjectId());
							if(projectDO != null && projectDO.getName() !=null){
								reininfo.setProjectName(projectDO.getName());
							}else{
								return R.error("请选择正确的项目");
							}
						}else {
							reininfo.setProjectId(-1L);
							reininfo.setProjectName("公司固定开销");
						}
						//查询费用类型
						PricetypeDO pricetypeDO = pricetypeService.get(reininfo.getAmountTypeid());
						if(pricetypeDO != null && pricetypeDO.getPrictType() !=null){
							reininfo.setAmountType(pricetypeDO.getPrictType());
						}
						reininfo.setGmtCreate(new Date());
						reininfo.setUserIdCreate(getUserId());
						reininfo.setUserNameCreate(getUser().getName());
						reimInfoService.save(reininfo);
					}
				}
				return R.ok();
			}else{
				return R.error();
			}
		}else{
			return R.error();
		}
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update( ReimDto reimDto){
		if(reimDto != null && reimDto.getId()>0){
			if(reimDto.getReimAmount() != null && reimDto.getReimAmount().compareTo(BigDecimal.ZERO)==1){
				String reimAmountCap = NumberToChineseUtil.getChineseNumber(reimDto.getReimAmount().doubleValue());
				reimDto.setReimAmountCap(reimAmountCap);
			}
			//编辑基础数据
			ReimDO reimDO = ReimDO.builder()
					.isInvoice(reimDto.getIsInvoice())
//					.deptId(reimDto.getDeptId())
					.reimAmount(reimDto.getReimAmount())
					.reimAmountCap(reimDto.getReimAmountCap())
					.reimDate(reimDto.getReimDate())
					.reimNumber(reimDto.getReimNumber())
					.writeoff(reimDto.getWriteoff())
					.reimTypeid(reimDto.getReimTypeid())
//					.reimUserid(reimDto.getReimUserid())
					.remark(reimDto.getRemark())
					.id(reimDto.getId())
					.build();
//			if(reimDO.getDeptId() != null && reimDO.getDeptId()>0){
//				reimDO.setDeptName(sysDeptService.getName(reimDO.getDeptId()));
//			}
//			if(reimDO.getReimUserid() != null && reimDO.getReimUserid()>0){
//				reimDO.setReimUsername(userService.getName(reimDO.getReimUserid()));
//			}
			int  updatenum = reimService.update(reimDO);
			if(updatenum>0){
				List<ReimInfoDO> reimInfoDOList = reimDto.getReimInfoDOList();
				if(reimInfoDOList != null && reimInfoDOList.size()>0){
					//开始保存明细信息
					for (ReimInfoDO reininfo:reimInfoDOList) {
						if(reininfo.getProjectId() != null && reininfo.getProjectId()>0){
							ProjectDO projectDO = projectService.get(reininfo.getProjectId());
							if(projectDO != null && projectDO.getName() !=null){
								reininfo.setProjectName(projectDO.getName());
							}else{
								return R.error("请选择正确的项目");
							}
						}else {
							reininfo.setProjectId(-1L);
							reininfo.setProjectName("公司固定开销");
						}
						//查询费用类型
						PricetypeDO pricetypeDO = pricetypeService.get(reininfo.getAmountTypeid());
						if(pricetypeDO != null && pricetypeDO.getPrictType() !=null){
							reininfo.setAmountType(pricetypeDO.getPrictType());
						}
						reininfo.setReimId(reimDO.getId());
						if(reininfo.getId()!= null && reininfo.getId()>0){
							reimInfoService.update(reininfo);
						}else{
							reininfo.setGmtCreate(new Date());
							reininfo.setUserIdCreate(getUserId());
							reininfo.setUserNameCreate(getUser().getName());
							reimInfoService.save(reininfo);
						}
					}
				}
			}

		}
		return R.ok();
	}
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	public R remove( Long id){
		if(reimService.updateStatus(6,id)>0){
			return R.ok();
		}
		return R.error();
	}

	@PostMapping( "/confirm")
	@ResponseBody
	public R confirm(Long id){
		int  status = 2;
		if(userService.isManagerOrCeo(getUserId())>0){
			status =3;
		}
		if(reimService.updateStatus(status,id)>0){
			return R.ok();
		}
		return R.error();
	}


	/**
	 * 审核
	 */
	@PostMapping( "/review")
	@ResponseBody
	public R review( Long id){
		if(reimService.updateStatus(3,id)>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 审核
	 */
	@PostMapping( "/endreview")
	@ResponseBody
	public R endreview( Long id){
		if(reimService.updateStatus(4,id)>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 审核
	 */
	@PostMapping( "/payment")
	@ResponseBody
	public R payment( Long id){
		if(reimService.updateStatus(5,id)>0){
			//付完款之后将项目相关的金额统计到项目中
			List<ReimInfoDO> reimInfoDOList = reimInfoService.findProjectPrice(id);
			if(reimInfoDOList != null && reimInfoDOList.size()>0){
				for (ReimInfoDO reinfo:reimInfoDOList) {
					//修改项目中的人员报销
					String message ="";
					DeviceAmountTwoDO deviceAmountTwoDO = deviceAmountTwoService.getProjectId(reinfo.getProjectId());
					if(deviceAmountTwoDO != null){
						message= "修改人员报销："+deviceAmountTwoDO.getSaleExpPrice()+"为："+(reinfo.getReimPrice());
						deviceAmountTwoDO.setSaleExpPrice(reinfo.getReimPrice());
						deviceAmountTwoService.update(deviceAmountTwoDO);
					}else{
						deviceAmountTwoDO = new DeviceAmountTwoDO();
						deviceAmountTwoDO.setSaleExpPrice(reinfo.getReimPrice());
						deviceAmountTwoDO.setProjectId(reinfo.getProjectId());
						deviceAmountTwoService.save(deviceAmountTwoDO);
						message= "新增人员报销："+reinfo.getReimPrice();
					}
					ProjectLogDO projectLogDO = new ProjectLogDO();
					projectLogDO.setGmtCreate(new Date());
					projectLogDO.setProjectId(reinfo.getProjectId());
					projectLogDO.setUserNameCreate(getUser().getName());
					projectLogDO.setUserIdCreate(getUserId());
					projectLogDO.setRemark(message);
//					projectLogDO.setProjectName(outstockDO.getPeojiectNumber());
					projectLogService.save(projectLogDO);
				}
			}
			return R.ok();
		}
		return R.error();
	}

	@PostMapping( "/overrule")
	@ResponseBody
	public R overrule( Long id){
		if(reimService.updateStatus(1,id)>0){
			return R.ok();
		}
		return R.error();
	}


	@GetMapping("/ckedit/{id}")
	String ckedit(@PathVariable("id") Long id,Model model){
		getEdit(id, model);
		return "fin/reim/ckedit";
	}


	@PostMapping("/exportData")
	@ResponseBody
	public void downloadTemplate(ReimDO reim, HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(StringUtils.isNotBlank(reim.getReimNumber())){
			params.put("reimNumber",reim.getReimNumber());
		}
		if(StringUtils.isNotBlank(reim.getReimUsername())){
			params.put("reimUsername",reim.getReimUsername());
		}
		if(reim.getReimDate() != null){
			params.put("reimDate",reim.getReimDate());
		}
		if(reim.getProjectid() != null){
			params.put("projectid",reim.getProjectid());
		}
		setOpenParms(params);
		List<ReimDO> reimDOList = reimService.list(params);
		for (ReimDO obj:reimDOList) {
			switch (obj.getStatus()){
				case 1:
					obj.setStatusname("新创建");
					break;
				case 2:
					obj.setStatusname("初审中");
					break;
				case 3:
					obj.setStatusname("终审中");
					break;
				case 4:
					obj.setStatusname("待付款");
					break;
				case 5:
					obj.setStatusname("已付款");
					break;
				case 6:
					obj.setStatusname("已删除");
					break;
				default:
					obj.setStatusname("新创建");
			}
		}
		ExcelUtil.exportExcel(reimDOList,"报销记录","报销记录",ReimDO.class,"报销记录.xls",response);
	}

	private void setOpenParms(Map<String, Object> params) {
		if (getUser().getDeptId() != 16 && getUser().getDeptId() != 23 && getUser().getDeptId() != 6) {//财务和总经理技术可以看所有
			//查询是否是部门经理
			int mgrcount = userService.isManager(getUserId());
			if (mgrcount > 0) {//部门经理看到部门下所有人的和自己的
				Map<String, Object> userparam = new HashMap<>();
				userparam.put("deptId", getUser().getDeptId());
				List<UserDO> userDOList = userService.list(userparam);
				List<Long> useridList = new ArrayList<>();
				for (UserDO userinfo : userDOList) {
					useridList.add(userinfo.getUserId());
				}
				params.put("userIdCreates", useridList);
			} else {
				params.put("userIdCreate", getUser().getUserId());
			}
		}
	}


	@GetMapping("/exportinfo/{id}")
	void exportinfo(@PathVariable("id") Long id,HttpServletResponse response){
		// 加载模板
		ReimDO reimDto = reimService.get(id);
		List<ReimInfoDO> reimInfoDOList = reimInfoService.findReimInfoByreimid(id);
		for (ReimInfoDO reimInfo:reimInfoDOList) {
			if(reimInfo.getInvoiceType() != null){
				ReimburseTypeDO reimburseTypeDO = reimburseTypeService.get(Long.valueOf(reimInfo.getInvoiceType()));
				reimInfo.setUserNameCreate(reimburseTypeDO.getName());
			}
			if(reimInfo.getTaxRate() == null){
				reimInfo.setTaxRate(new BigDecimal("0"));
			}
		}
		String fileNmae = "报销明细";
		TemplateExportParams param = new TemplateExportParams("/excelTemplates/reimidTemplants.xlsx", true);

		Map<String, Object> map = new HashMap<>();
		map.put("reimUsername",reimDto.getReimUsername());
		map.put("deptName",reimDto.getDeptName());
		map.put("reimNumber",reimDto.getReimNumber());
		map.put("reimAmount",reimDto.getReimAmount());
		map.put("reimDate",reimDto.getReimDate());
		map.put("reimAmountCap",reimDto.getReimAmountCap());
		map.put("list", reimInfoDOList);
		try {
			Workbook book = ExcelExportUtil.exportExcel(param, map);
			//下载方法
			ExcelUtil.export(response, book, fileNmae);
		} catch (Exception e) {
			System.out.println("导出模板Excel，失败:" + e);
		}
	}


	@PostMapping("/exportDataByProject")
	@ResponseBody
	@RequiresPermissions("fin:reim:exportDataByProject")
	public void downloadTemplate(ReimInfoDO reimInfo, HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(reimInfo.getProjectId() != null){
			params.put("projectId",reimInfo.getProjectId());
		}
		List<ReimInfoDO> reimInfoDOList = reimInfoService.downloadTemplate(params);
		ExcelUtil.exportExcel(reimInfoDOList,"报销明细记录","报销明细记录",ReimInfoDO.class,"报销明细记录.xls",response);
	}

	@GetMapping("/getSalExpprice/{projectId}")
	@ResponseBody
	public Double  getSalExpprice(@PathVariable("projectId") Long projectId){
		Double salExprice = reimInfoService.getSalExpprice(projectId);
		if(salExprice == null){
			salExprice = 0D;
		}
		return salExprice;
	}
}
